package com.ly.hotel.view.fragments.query;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.Weather;
import com.ly.hotel.util.DateUtils;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.common.BaseActivity;
import com.ly.hotel.view.setting.SystemSettingActivity;
import com.ly.hotel.webagent.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WeatherActivity extends BaseActivity {

	private Handler handler;
	private LinearLayout top;
	private LinearLayout bottom;
	private ListView areaList;
	private ImageButton searchBtn;
	private EditText editText;
	private ListView weathersList;
	private TextView cityName;
	private MyApplication app;
	private List<AreaMsgBean> areaMsgBeanList;
	private AreaAdapter areaAdapter;
	private WeathersAdapter weathersAdapter;
	private String sAreaName;
	private List<Weather> weathers = new ArrayList<>();
	private boolean isFirst = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wether);
		app = (MyApplication) getApplicationContext();
		findView();
		setListener();
		setAdapter();
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what){
					case 1:
						String id = msg.obj.toString();
						StringBuilder sb = new StringBuilder(id);
						// 由于天气API的接口不支持查询区，把区的城市代码全部替换成该市的
						String newId = sb.replace(id.length() - 3,id.length() + 1,"000").toString();
						getWeather(newId);
						break;
					case 2:
						ProcessWaitingUtil.closeProcessDialog();
						setWeathersAdapter(sAreaName,weathers);
						break;
					case 99:
						ProcessWaitingUtil.closeProcessDialog();
						ToastUtil.showShortToast(WeatherActivity.this,"查询出错！Error!",3000);
						break;
					default:
						break;
				}
			}
		};
		if(!TextUtils.isEmpty(app.areaName) && app.weathers.size() > 0) {
			setWeathersAdapter(app.areaName,app.weathers);
		}
	}
	
	@Override
	public void finish() {
		super.finish();
	}
	
	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}


	@Override
	public void onResume() {
		super.onResume();		
	}

	private void findView() {
		top = findViewById(R.id.top_more);
		bottom = findViewById(R.id.bottom_more);
		areaList = findViewById(R.id.area_list);
		weathersList = findViewById(R.id.weather_list);
		searchBtn = findViewById(R.id.search_btn);
		editText = findViewById(R.id.search_edit);
		cityName = findViewById(R.id.city_name);
	}

	private void setListener() {

		areaList.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				checkPos();
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});

		areaList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				checkPos();
				if (handler.hasMessages(1)){
					handler.removeMessages(1);
				}
				if(!isFirst) {
					Message message = new Message();
					message.what = 1;
					message.obj = areaAdapter.getMyItem(position).getId();
					sAreaName = areaAdapter.getMyItem(position).getName();
					handler.sendMessageDelayed(message, 1500);
				}
				isFirst = false;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				checkPos();
			}
		});

		areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (handler.hasMessages(1)){
					handler.removeMessages(1);
				}
				Message message = new Message();
				message.what = 1;
				message.obj =  areaAdapter.getMyItem(position).getId();
				sAreaName = areaAdapter.getMyItem(position).getName();
				handler.sendMessage(message);
			}
		});


		searchBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String ss = editText.getText().toString();
				if (!TextUtils.isEmpty(ss)){
					ss = ss.toUpperCase();
					List<AreaMsgBean> abL = new ArrayList<>();
					for (AreaMsgBean ab : areaMsgBeanList){
						if (ab.getName().toUpperCase().contains(ss)){
							abL.add(ab);
						}
					}
					ProcessWaitingUtil.showProcessDialog(WeatherActivity.this,"Loading...",10000);
					setList(abL);
				}
			}
		});

	}

	//判断释放需要显示上下滑动提示
	private void checkPos(){
		if (areaList.canScrollVertically(1)){
			bottom.setVisibility(View.VISIBLE);
		}else{
			bottom.setVisibility(View.INVISIBLE);
		}

		if (areaList.canScrollVertically(-1)){
			top.setVisibility(View.VISIBLE);
		}else{
			top.setVisibility(View.INVISIBLE);
		}
	}

	private void setAdapter() {
		ProcessWaitingUtil.showProcessDialog(this,"Loading...",10000);
		areaMsgBeanList = app.areaMsgBeanList;
		if (areaMsgBeanList.size() == 0) {
			String sendRes = SystemSettingActivity.getJson(this, "earth.json");
			try {
				JSONArray jArr = new JSONArray(sendRes);
				for (int i = 0; i < jArr.length(); i++) {
					JSONObject obj = jArr.getJSONObject(i);
					String name = obj.getString("name");
					String id = obj.getString("id");
					String nameEn = obj.getString("en");
					AreaMsgBean ab = new AreaMsgBean(id,name,nameEn);
					areaMsgBeanList.add(ab);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		setList(areaMsgBeanList);
	}

	private void getWeather(final String id){
		ProcessWaitingUtil.showProcessDialog(this,"Loading...",10000);
		new Thread(new Runnable() {
			@Override
			public void run() {
				/*String URL = "http://tj.nineton.cn/Heart/index/all";
				String req = "city=" + id;*/
				String language = "zh-Hans";
				if(MyApplication.currectLocale.equals(Locale.SIMPLIFIED_CHINESE)){
					language = "zh-Hans";
				}else if(MyApplication.currectLocale.equals(Locale.TRADITIONAL_CHINESE)){
					language = "zh-Hant";
				}else if(MyApplication.currectLocale.equals(MyApplication.currectLocale)){
					language = "en";
				}
				String URL = "https://api.seniverse.com/v3/weather/daily.json";
				String req = "key=5ovomx2kui2x6ayt&location=" + id + "&language=" + language +
						"&unit=c&start=0&days=3";
				Log.i("httpGet",URL + "?" + req);
				String sendRes = HttpRequest.sendGet(URL,req);
				try {
					JSONObject jsonObject = new JSONObject(sendRes);
					JSONArray jsonArray = jsonObject.getJSONArray("results");
					JSONObject jsonObject2 = jsonArray.getJSONObject(0);

					JSONArray dailyArray = jsonObject2.getJSONArray("daily");
					weathers.clear();
					for(int i = 0;i < dailyArray.length();i ++){
						JSONObject object = dailyArray.getJSONObject(i);
						Weather weather = new Weather();
						weather.setArea("");
						weather.setAreaEn("");
						weather.setDate(object.getString("date"));
						weather.setwCode(object.getString("code_day"));
						weather.setwCode2(object.getString("code_night"));
						weather.setLow(object.getString("low"));
						weather.setHeight(object.getString("high"));
						weathers.add(weather);
					}
					handler.sendEmptyMessage(2);
				} catch (JSONException e) {
					handler.sendEmptyMessage(99);
				}
			}
		}).start();
	}

	private void setList(List<AreaMsgBean> al){
		if(areaAdapter == null){
			areaAdapter = new AreaAdapter(this);
			areaAdapter.setList(al);
			areaList.setAdapter(areaAdapter);
		}else {
			areaAdapter.setList(al);
			areaAdapter.notifyDataSetChanged();
		}
		areaList.post(new Runnable() {
			@Override
			public void run() {
				ProcessWaitingUtil.closeProcessDialog();
				checkPos();
			}
		});
	}

	private void setWeathersAdapter(String name,List<Weather> wL){
		cityName.setText(LanguageUtil.getTextFromLocalLanguage(name));
		if(weathersAdapter == null){
			weathersAdapter = new WeathersAdapter(this);
			weathersAdapter.setList(wL);
			weathersList.setAdapter(weathersAdapter);
		}else {
			weathersAdapter.setList(wL);
			weathersAdapter.notifyDataSetChanged();
		}
	}

	class AreaAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<AreaMsgBean> aList;

		public AreaAdapter(Context c) {
			mInflater = LayoutInflater.from(c);
		}

		public void setList(List<AreaMsgBean> al){
			aList = al;
		}

		@Override
		public int getCount() {
			return aList.size();
		}

		@Override
		public Object getItem(int postion) {
			return aList.get(postion);
		}

		@Override
		public long getItemId(int postion) {
			return postion;
		}

		public AreaMsgBean getMyItem(int pos){
			return aList.get(pos);
		}

		@Override
		public View getView(int position, View contentView, ViewGroup arg2) {
			ViewHolder holder;

			if (contentView == null) {

				holder = new ViewHolder();
				contentView = mInflater.inflate(R.layout.vod_btn_item, null);
				holder.mbtn = contentView.findViewById(R.id.m_vod_item_btn);
				contentView.setTag(holder);
			} else {
				holder = (ViewHolder) contentView.getTag();
			}
			holder.mbtn.setTextColor(Color.parseColor("#eeeeee"));
			String name = LanguageUtil.getTextFromLocalLanguage(aList.get(position).getName());
			holder.mbtn.setText(name);
			return contentView;
		}

		class ViewHolder {
			TextView mbtn;
		}
	}

	class WeathersAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<Weather> wList;
		private DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

		public WeathersAdapter(Context c) {
			mInflater = LayoutInflater.from(c);
		}

		public void setList(List<Weather> al){
			wList = al;
		}

		@Override
		public int getCount() {
			return wList.size();
		}

		@Override
		public Object getItem(int postion) {
			return wList.get(postion);
		}

		@Override
		public long getItemId(int postion) {
			return postion;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup arg2) {
			ViewHolder holder;

			if (contentView == null) {
				holder = new ViewHolder();
				contentView = mInflater.inflate(R.layout.weather_list_item, null);
				holder.mDate = contentView.findViewById(R.id.weather_date);
				holder.mImg = contentView.findViewById(R.id.weather_img);
				holder.mWaether = contentView.findViewById(R.id.weather_wName);
				contentView.setTag(holder);
			} else {
				holder = (ViewHolder) contentView.getTag();
			}


			Weather weather = wList.get(position);
			String wN;
			String wN1 = app.getWeatherName(weather.getwCode()).getName() + ";" +
					app.getWeatherName(weather.getwCode()).getNameEn();
			String wN2 = app.getWeatherName(weather.getwCode2()).getName() + ";" +
					app.getWeatherName(weather.getwCode2()).getNameEn();
			int imgId = app.getWeatherName(weather.getwCode()).getImg();
			String dt = weather.getDate();
			if (LanguageUtil.getTextFromLocalLanguage(wN1).equals(LanguageUtil.getTextFromLocalLanguage(wN2))) {
				wN = LanguageUtil.getTextFromLocalLanguage(wN1) + "\n" + weather.getLow() + " — " + weather.getHeight() + " ℃";
			} else {
				wN = LanguageUtil.getTextFromLocalLanguage(wN1) + " — " + LanguageUtil.getTextFromLocalLanguage(wN2)
						+ "\n" + weather.getLow() + " — " + weather.getHeight() + " ℃";
			}

			Date mDt;
			try {
				mDt = format1.parse(dt);
				dt = DateUtils.getDateString(mDt, getResources());
			} catch (ParseException e) {
				e.printStackTrace();
			}

			holder.mDate.setText(dt);
			holder.mWaether.setText(wN);
			holder.mImg.setImageResource(imgId);
			return contentView;
		}

		class ViewHolder {
			TextView mDate;
			ImageView mImg;
			TextView mWaether;
		}
	}

}
